package cn.virens.common.util.fastjson.filter;

import cn.virens.common.util.core.objcet.ObjectUtil;
import cn.virens.common.util.exception.APIException;
import com.alibaba.fastjson2.filter.ValueFilter;

import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Function;

public class VirensValueFilter implements ValueFilter {
    public final static VirensValueFilter instance = new VirensValueFilter();

    private final Map<Class<?>, ValueFilter> assemble = new ConcurrentHashMap<>();

    /**
     * 注册指定类型的处理逻辑
     */
    public static ValueFilter put(Class<?> key, ValueFilter value) {
        return instance.assemble.put(key, value);
    }

    /**
     * 注册指定类型的处理逻辑
     */
    public static ValueFilter put(Class<?> key, Function<Object, Object> value) {
        return instance.assemble.put(key, (o, n, v) -> value.apply(v));
    }

    /**
     * 注册指定类型的处理逻辑
     */
    public static ValueFilter put(Class<?> key, BiFunction<String, Object, Object> value) {
        return instance.assemble.put(key, (o, n, v) -> value.apply(n, v));
    }

    @Override
    public Object apply(Object object, String name, Object value) throws APIException {
        for (Entry<Class<?>, ValueFilter> entry : assemble.entrySet()) {
            if (ObjectUtil.isAssignableFrom(value, entry.getKey())) {
                return entry.getValue().apply(object, name, value);
            }
        }

        return value;
    }

}
